<?php

/**
 * DYSHOP
 * ============================================================================
 * 版权所有 2005-2028 杭州鼎易信息科技有限公司，并保留所有权利。
 * 网站地址: https://www.doing.net.cn
 * ==========================================
 * 本系统由鼎易科技团队开发 156791994@qq.com
 * ============================================================================
 * $Author: TANGYIN 2020-06-06 $
 *
 */
namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Config;
use think\facade\Session;

use app\BaseController;

class Base  extends BaseController
{
    public $page_size = 0;
    public $admin_id = 0;
    public $admin_siteid = 1;
    public $admin_site_name = '中文站';
    /**
     * 析构函数
     */
    function __construct(){
        header("Cache-control: private");

        Request::isAjax() ? define('IS_AJAX',true) : define('IS_AJAX',false);  //
        (Request::method() == 'GET') ? define('IS_GET',true) : define('IS_GET',false);  //
        (Request::method() == 'POST') ? define('IS_POST',true) : define('IS_POST',false);  //

        define("DOMAIN",Request() -> domain());
        define('MODULE_NAME',app('http')->getName());  // 当前模块名称是
        define('CONTROLLER_NAME',Request::controller()); // 当前控制器名称
        define('ACTION_NAME',Request::action()); // 当前操作名称是

        define('PREFIX', config('database.connections.mysql.prefix')); // 数据库表前缀
        define('DATABASE', config('database.connections.mysql.database')); // 数据库名

        View::assign('action',ACTION_NAME);
        View::assign('template_now_time', time());//模板现在时间

        define('RUNTIME_PATH',root_path().'runtime' ); // 数据库表前缀
        define('APP_PATH', base_path());// 定义应用目录
        define('ROOT_PATH', root_path());// 定义应用目录

        //dump(Session::get('admin_siteid'));

        //config设置
        $webconfig = DB::name("webconfig")->select();
        $webconfig_arr = [];
        foreach($webconfig as $v){
            $webconfig_arr[$v['varname']] = $v['varvalue'];
        }
        Config::set($webconfig_arr, 'webconfig');
        //dump($webconfig_arr);

        //站点
        if(Session::has('admin_siteid')){
            $this->admin_siteid = Session::get('admin_siteid');
            define('ADMIN_SITEID',Session::get('admin_siteid'));
            //站点标识
            $ty_site_name = DB::name('site')->where('site_id',$this->admin_siteid)->find();
            $this->admin_site_name = $ty_site_name['name'];
            $this->admin_site_key = $ty_site_name['key'];
        }else{
            $this->admin_siteid = 1;
            define('ADMIN_SITEID',1);
            $this->admin_site_name = '中文站';
            $this->admin_site_key = 'ch';
        }

        View::assign('admin_siteid',$this->admin_siteid);
        View::assign('admin_site_name',$this->admin_site_name);
        View::assign('admin_site_key',$this->admin_site_key);

        //过滤不需要登陆的行为
        if (!in_array(ACTION_NAME, array('login', 'vertify'))) {
            if (session('admin_id') > 0) {
                $this->check_priv();//检查管理员菜单操作权限
                $this->admin_id = session('admin_id');
            }else {
                //if(ACTION_NAME == 'index') return redirect( url('Admin/login'));
//                $this->error('请先登录', url('Admin/login'), null, 1);
                $this -> redirect( url('Admin/login'));
            }
        }

        /*//用户中心面包屑导航
        $navigate_admin = navigate_admin();
        View::assign('navigate_admin',$navigate_admin);
        //过滤不需要登陆的行为 
        if (!in_array(ACTION_NAME, array('login', 'vertify'))) {
            if (session('admin_id') > 0) {
                $this->check_priv();//检查管理员菜单操作权限
                $this->admin_id = session('admin_id');
                $this->admin_company_id = session('company_id');
            }else {
                //if(ACTION_NAME == 'index') return redirect( url('Admin/login'));
                $this->error('请先登录', url('Admin/login'), null, 1);
            }
        }
        $this->public_assign();*/
        // 控制器初始化
        $this->initialize();
    }

    /**
     * 保存公告变量到 smarty中 比如 导航 
     */
    /*public function public_assign(){
       $dyshop_config = array();
       $dy_config = Db::name('config')->cache(true, DYSHOP_CACHE_TIME, 'config')->select();
       if($dy_config){
           foreach($dy_config as $k => $v){
               $dyshop_config[$v['inc_type'].'_'.$v['name']] = $v['value'];
           }
       }
        $this->page_size = input('limit/d',config('PAGESIZE'));
        View::assign('dyshop_config', $dyshop_config);
        $isauth = false;
        if(session('admin_id') == 1) $isauth = true;
        View::assign('isauth',$isauth);
        //权限
        if (session('admin_id') > 1) {
            $act_list = session('act_list');
            $group = Db::name('system_menu')->where("id", "in", $act_list)->cache(false)->column('group');
            if (isset($group['system']) && $group['system'] == 'system') {
                $right['system'] = 1;
            } else {
                $right['system'] = 0;
            }
            if (isset($group['order']) && $group['order'] == 'order') {
                $right['order'] = 1;
            } else {
                $right['order'] = 0;
            }
            if (isset($group['content']) && $group['content'] == 'content') {
                $right['content'] = 1;
            } else {
                $right['content'] = 0;
            }
        } else {
            $right['system'] = 1;
            $right['order'] = 1;
            $right['content'] = 1;
            $right['device'] = 1;
            $right['user'] = 1;
        }
        View::assign('right', $right);
        if($this->admin_company_id==$this->parent_company_id){
            $this->is_company = 1;
        }
        View::assign('is_company', $this->is_company);
        View::assign('admin_company_id', $this->admin_company_id);
        $company = get_company_list();
        View::assign('company',$company);
        View::assign('limits',json_encode($this->limits));
        View::assign('page_size',$this->page_size);
        View::assign('order_type',config('order_type'));
        View::assign('order_status',config('order_status'));
        $this->audit_status = config('audit_status');
        View::assign('audit_status',$this->audit_status);
        //审核选择
        $audit = Db::name('admin')->field('admin_id,contacts,user_name')->select()->toArray();
        View::assign('audit',$audit);
        //付款方式
        View::assign('pay_type', config('pay_type'));
    }*/
    
    public function check_priv(){
    	$ctl = CONTROLLER_NAME;
    	$act = ACTION_NAME;
        $act_list = session('act_list');
		//无需验证的操作
		$uneed_check = array('login','logout','vertifyHandle','vertify','imageUp','upload','videoUp','delupload','login_task','updatePwd');
    	if($ctl == 'Index' || $act_list == 'all' || $ctl == 'Wx3rd'){
    		//后台首页控制器无需验证,超级管理员无需验证
    		return true;
    	}elseif((request()->isAjax() && $this->verifyAjaxRequest($act)) || strpos($act,'ajax')!== false || in_array($act,$uneed_check)){
    		//部分ajax请求不需要验证权限
            if($act == 'CloseOrder' || $act == 'OrderRefund'){
                $res = $this->verifyAction();
                if($res['status'] == -1){
                    return dyajaxReturn(0, $res['msg']);
                };
            }
    		return true;
    	}else{
            $res = $this->verifyAction();
    		if($res['status'] == -1){
                $this->error($res['msg'],$res['url']);
            };
    	}
    }
    
    public function ajaxReturn($data,$type = 'json'){                        
        exit(json_encode($data,JSON_UNESCAPED_UNICODE));
    }

    /**
     * 要验证的ajax
     * @param $act
     * @return bool
     */
    private function verifyAjaxRequest($act){
        $verifyAjaxArr = ['delGoodsCategory','delGoodsAttribute','delGoods','supertube_order'];
        if(request()->isAjax() && in_array($act,$verifyAjaxArr)){
            $res = $this->verifyAction();
            if($res['status'] == -1){
                $this->ajaxReturn($res);
            }else{
                return true;
            };
        }else{
            return true;
        }
    }
    private function verifyAction(){
        $ctl = CONTROLLER_NAME;
        $act = ACTION_NAME;
        $act_list = session('act_list');
        $right = Db::name('system_menu')->where("id", "in", $act_list)->cache(false)->column('right');
        $role_right = $htmlright = '';
        foreach ($right as $val){
            $role_right .= $val.',';
            $htmlright .= str_replace("@","##",$val).',';
        }
        $role_right = explode(',', $role_right);
        $htmlright = explode(',', $htmlright);

        //检查是否拥有此操作权限
        if(! ( in_array($ctl.'@'.$act, $role_right) || in_array(strtolower($ctl).'@'.$act, $role_right) )  ){
            //return ['status'=>-1,'msg'=>'您没有操作权限['.($ctl.'@'.$act).'],请联系超级管理员分配权限','url'=>url('Admincp/Index/welcome')];
            return ['status'=>-1,'msg'=>'您没有操作权限,请联系管理员分配权限','url'=>url('Admin/Index/welcome')];
        } 
        View::assign('htmlright',$htmlright);
        session('htmlright',$htmlright);
        return ['status'=>1,'msg'=>'您有操作权限'];
    }


    public function changeStatus(){
        $param = input('param.');
        $table = $param['table'];
        $id_name = $param['id_name'];
        $id = $param['id'];
        $field = $param['field'];
        $checked = $param['checked'];

        if($checked == 'true'){
            $res = DB::name($table) -> where($id_name,'=',$id)->update([$field=>1]);
        }else{
            $res = DB::name($table) -> where($id_name,'=',$id)->update([$field=>2]);
        }
        if(!$res){
            return dyajaxReturn(0,'操作失败');
        }
        return dyajaxReturn(1,'操作成功');
    }

    public function changeOrderid(){
        $param = input('param.');
        $table = $param['table'];
        $id_name = $param['id_name'];
        $id = $param['id'];
        $field = $param['field'];
        $val = $param['val'];

        $res = DB::name($table) -> where($id_name,'=',$id)->update([$field=>$val]);
        if(!$res){
            return dyajaxReturn(0,'操作失败');
        }
        adminLog($table.'表的排序修改为'.$val,$id);
        return dyajaxReturn(1,'操作成功');
    }




}